package cn.fch.gotrip.util;

import cn.fch.gotrip.entity.Admin;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

/**
 * @program: gotrip
 * @description:
 * @CreatedBy: fch
 * @create: 2023-01-14 23:41
 **/
@Component
public class JwtUtil {
    //SECRET 数字签名密钥
    private final static String SECRET = "gotrip";
    //EXPIRE 7天有效期
    private final static long EXPIRE = 1000 * 60 * 60 * 24;
    //EXPECT 还有最后一天到期时刷新
    private final static long EXPECT = 1000 * 60 * 60 * 24;

    /**
     * 解析token
     *
     * @param token 需要解析的
     * @return Claims
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
            //过期等token无效
            claims = null;
        }
        return claims;
    }

    /**
     * 构建认证过的认证对象
     *
     * @param jws
     * @return
     */
/*    public UsernamePasswordAuthenticationToken buildAuthentication(Claims jws) {
        String userName;
        String role;
        userName = jws.getSubject();

        //从token中获得角色信息
        role = jws.get("role", String.class);

        List<SimpleGrantedAuthority> roleList
                = Stream.of(Optional.ofNullable(role).orElse("").split(","))
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        //返回合法认证对象
        return new UsernamePasswordAuthenticationToken(userName, null, roleList);
    }*/
    public Admin getAdminInfo(Claims jws) {
        if (null == jws)
            return null;
        Admin adminInfo = new Admin();
        adminInfo.setUsername(jws.getSubject());
        adminInfo.setRole(jws.get("role", String.class));
        adminInfo.setAvatar("http://localhost:8080/static/img/admin-avatar/" + jws.get("avatar", String.class) + ".png");
        //从token中获得角色信息
        return adminInfo;
    }

    /**
     * 生成 jwt token
     *
     * @param username
     * @param role
     * @return
     */
    public String generatorToken(String username, String role, String avatar) {
        //生成token
        return Jwts.builder()
                .setSubject(username) //填写令牌的用户名
                .claim("role", role) //填写角色
                .claim("avatar", avatar) //填写角色
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) //有效日期
                .signWith(SignatureAlgorithm.HS512, SECRET) //数字签名
                .compact();
    }

    /**
     * 判断 token 是否要刷新
     *
     * @param token
     * @return true:该刷新了
     */
    public boolean isRefress(Claims token) {
        return token.getExpiration().before(new Date(System.currentTimeMillis() + EXPECT));
    }
}
